package com.bonc.sign.utils;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import static com.bonc.sign.constants.Constants.*;

public class QueryStringUtils {

	/**
	 * 从url获取queryString
	 *
	 * @param url
	 * @return
	 */
	public static String[] parseUrl(String url) {
		String[] qs = new String[2];
		if (url != null && url.contains(QS_QM)) {
			qs[0] = StringUtils.substringBefore(url, QS_QM);
			qs[1] = StringUtils.substringAfter(url, QS_QM);
		}else{
			qs[0] = url;
		}
		return qs;
	}

	/**
	 * 从queryString解析参数的map
	 *
	 * @param queryString
	 * @return
	 */
	public static Map<String, Object> parse(String queryString) {
		Map<String, Object> qsMap = new HashMap<>();
		if (StringUtils.isNotBlank(queryString)) {
			String[] params = StringUtils.split(queryString, QS_AND);
			for (String param : params) {
				String[] valuePair = StringUtils.split(param, QS_EQ, 2);
				if (valuePair != null) {
					if (valuePair.length == 1) {
						qsMap.put(valuePair[0], "");
					} else if (valuePair.length == 2) {
						qsMap.put(valuePair[0], valuePair[1]);
					}
				}
			}
		}
		return qsMap;
	}

	/**
	 * 剔除不参与排序的进行排序输出为queryString格式
	 *
	 * @param qsMap
	 * @param excluded 没有排除的则全排序
	 * @return
	 */
	public static String sortExcluded(Map<String, Object> qsMap, String... excluded) {
		String newQueryString = qsMap == null ? "" : StringUtils.join(
				qsMap.keySet().stream().sorted().filter(x -> excluded == null || !ArrayUtils.contains(excluded, x))
						.map(k -> {
							return k + QS_EQ + qsMap.get(k);
						}).collect(Collectors.toList()), QS_AND);
		return newQueryString;
	}

	/**
	 * 包含参与排序的输出为queryString格式
	 *
	 * @param qsMap
	 * @param included 没有包含的则全排序
	 * @return
	 */
	public static String sortIncluded(Map<String, Object> qsMap, String... included) {
		String newQueryString = qsMap == null ? "" : StringUtils.join(
				qsMap.keySet().stream().sorted().filter(x -> included == null || ArrayUtils.contains(included, x))
						.map(k -> {
							return k + QS_EQ + qsMap.get(k);
						}).collect(Collectors.toList()), QS_AND);
		return newQueryString;
	}

	public static void main(String[] args) throws Exception {
		String qs = "test1=1&abcd=2&sign=aG9zcGl0YWxJZD3kuK3mlocmd+GltZXN0Y" +
				"/W1wPTE3MDI5NzE3MTcxMzA" + "=&timestamp=1702953073993&best=3";
		System.out.println(sortExcluded(parse(qs), "sign"));

	//	System.out.println(EncryptUtils.sign("AES", "tGuWgUr8PaS3dl7m", sortExcluded(parse(qs), "sign"), "UTF-8"));
	}
}
